package org.magicbox.qjunTPO.controller;


import org.magicbox.qjunTPO.common.lang.Result;
import org.magicbox.qjunTPO.entity.Supuser;
import org.magicbox.qjunTPO.entity.User;
import org.magicbox.qjunTPO.service.SupuserService;
import org.magicbox.qjunTPO.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 欢迎添加科技实践队粉丝群：690849711
 * @since 2021-11-12
 */
@RestController
@RequestMapping("/supuser")
public class SupuserController {
    @Autowired
    SupuserService supuserService;

    @Autowired
    UserService userService;

    @Autowired
    PasswordEncoder pw;

    /**
     * 管理员修改用户marker
     * @param supuser   管理员实体
     * @param uid   用户id
     * @param marker    用户新marker
     * @return      结果
     */
    @PreAuthorize("hasAnyAuthority('UserPower')")
    @RequestMapping(value = "/updateMarkerById",method = RequestMethod.POST)
    public Result updateMarkerById(@Validated @RequestBody Supuser supuser,
                                   @PathParam("uid") Integer uid,
                                   @PathParam("marker")Integer marker) {
        //验证管理员信息
        if(supuserService.passowrdProving(supuser)&
                supuserService.exPower(supuser.getSuId(),4)) {
            if(userService.updateMarkerById(uid,marker)) return Result.success("修改成功");
            else return Result.fail("失败了!");
        }
        else return Result.fail("操作失败");
    }


    /**
     * 增加管理员
     * @param supuser 增加的管理员
     * @return      结果
     */
    @PreAuthorize("hasAnyAuthority('SuperPower')")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Result add(@Validated @RequestBody Supuser supuser){
            if (supuserService.exSuper(supuser.getSuId())) {
                return Result.fail("已经存在该用户");
            }
            supuser.setPassword(pw.encode(supuser.getPassword()));
            supuserService.save(supuser);
            return Result.success(supuser);
    }



}
